package com.kehao.netease;

import java.util.*;

public class Q4 {
    static int result = 0;
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String[] s1 = sc.nextLine().split(" ");
        int nodeCount = Integer.parseInt(s1[0]);
        int start = Integer.parseInt(s1[1]);
        int lineCount = Integer.parseInt(s1[2]);
        Map<Integer, PriorityQueue<int[]>> map = new HashMap<>();
        int[] visited = new int[nodeCount];
        for (int i = 0; i < lineCount; i++) {
            s1 = sc.nextLine().split(" ");
            PriorityQueue<int[]> queue = map.computeIfAbsent(Integer.parseInt(s1[0]), k -> new PriorityQueue<>((arr1,arr2)->arr1[1]-arr2[1]));
            queue.add(new int[]{Integer.parseInt(s1[1]),Integer.parseInt(s1[2])});
        }
        dfs(map, visited,start,result);
        for (int i = 0; i < visited.length; i++) {
            if(visited[i]==0){
                System.out.println(-1);
                return ;
            }
        }
        System.out.println(result);
    }

    private static void dfs(Map<Integer, PriorityQueue<int[]>> map, int[] visited, int start, int result) {
        if(visited[start]==1){
            return;
        }
        Q4.result = Integer.max(result,Q4.result);
        visited[start]=1;
        PriorityQueue<int[]> priorityQueue = map.get(start);
        if(priorityQueue!=null){
            while (!priorityQueue.isEmpty()){
                int[] poll = priorityQueue.poll();
                dfs(map,visited,poll[0], result+poll[1]);
            }
        }

    }
}
